<template>
  <Dialog
    v-if="dialogVisible"
    v-model="dialogVisible"
    maxHeight="80vh"
    width="92vw"
    :title="t('common.select')"
    :before-close="() => closeDialog()"
    class="mobile-dialog"
  >
    <!--    顶部查询项-->
    <el-form :model="form" inline class="mobile-form">
      <el-form-item :label="t('wholesalOrder.productName')">
        <el-input
          v-model="form.product"
          clearable
          :disabled="isDisabledProduct"
          :placeholder="t('wholesalOrder.productName')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.warehouse')">
        <el-select
          v-model="form.wid"
          :placeholder="t('wholesalOrder.warehouse')"
          clearable
          filterable
          :disabled="isDisabledWid"
          style="width: 250px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.brand')">
        <el-select
          v-model="form.brand"
          :placeholder="t('wholesalOrder.brand')"
          clearable
          :disabled="isDisabledProduct"
          style="width: 250px"
        >
          <el-option
            v-for="item in brandList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.type')">
        <el-select
          v-model="form.is_futures"
          :placeholder="t('wholesalOrder.type')"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in warehouseTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.arrivalDate')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          @change="changeTime"
          :editable="false"
          unlink-panels
          clearable
        />
      </el-form-item>
      <el-form-item>
        <div class="mobile-button-group horizontal">
          <el-button type="primary" icon="Search" @click="getList">{{
            t('common.query')
          }}</el-button>
          <el-button icon="Refresh" @click="reset(true)">{{ t('common.reset') }}</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 移动端商品卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card
        v-for="item in dataList"
        :key="item.unique"
        class="product-card"
        :class="{
          'sale-card': item.is_sale === 0 || item.is_sale === '0' || item.is_sale === false
        }"
      >
        <template #header>
          <div class="card-header">
            <span class="product-name">{{ item.product_name }}</span>
            <el-checkbox v-model="item.checked" @change="handleCardSelection(item)" />
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.computingPower') }}:</span>
            <span class="value">{{ item.hashrate }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.warehouse') }}:</span>
            <span class="value">{{ useEnumeratePicker(warehouseList, item.wid) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('MerchandiseOffersBaskets.is_sale') }}:</span>
            <span class="value">{{ item.is_sale ? t('common.yes') : t('common.no') }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.sellableInventory') }}:</span>
            <span class="value">{{ item.quantity }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.brand') }}:</span>
            <span class="value">{{ useEnumeratePicker(brandList, item.brand) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.type') }}:</span>
            <span class="value">{{ useEnumeratePicker(warehouseTypeList, item.is_futures) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.arrivalDate') }}:</span>
            <span class="value">{{ item.arrival_date }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.cost') }}:</span>
            <span class="value">{{ item.original_price }}</span>
          </div>
          <div class="info-row">
            <span class="label">头程物流费:</span>
            <span class="value">{{ item.first_leg_logistics_fee }}</span>
          </div>
          <div class="info-row" v-if="form.currency">
            <span class="label">币种:</span>
            <span class="value">{{ item.actual_quoted_currency_name }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 桌面端表格视图 -->
    <div v-else class="mobile-table">
      <el-table
        class="m-t-10px"
        :data="dataList"
        highlight-current-row
        stripe
        border
        ref="tableRef"
        v-loading="tableLoading"
        row-key="unique"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        :row-class-name="getRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55" />
        <el-table-column
          :label="t('wholesalOrder.productName')"
          prop="product_name"
          :width="calculateColumnWidth(dataList, 'product_name', 1, 6)"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.computingPower')"
          prop="hashrate"
          :width="calculateColumnWidth(dataList, 'hashrate')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.warehouse')"
          min-width="160"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseList, row.wid) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('MerchandiseOffersBaskets.is_sale')"
          prop="is_sale"
          :width="calculateColumnWidth(dataList, 'is_sale')"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.is_sale ? t('common.yes') : t('common.no') }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.sellableInventory')"
          prop="quantity"
          :show-overflow-tooltip="true"
          min-width="118"
        >
          <template #default="{ row }">
            {{ `${row.quantity} ${row.share_id ? '（共享）' : ''}` }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.brand')"
          min-width="80"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(brandList, row.brand) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('wholesalOrder.type')" width="100" :show-overflow-tooltip="true">
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseTypeList, row.is_futures) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.arrivalDate')"
          prop="arrival_date"
          min-width="86"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('order.realArrivalDate')"
          prop="real_arrival_date"
          min-width="86"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.cost')"
          prop="original_price"
          :width="calculateColumnWidth(dataList, 'original_price')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('inventory.first_leg_logistics_fee')"
          prop="first_leg_logistics_fee"
          :width="calculateColumnWidth(dataList, 'first_leg_logistics_fee')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-if="form.currency"
          :label="t('product.currency')"
          prop="actual_quoted_currency_name"
          min-width="80"
          :show-overflow-tooltip="true"
        />
      </el-table>
    </div>

    <template #footer>
      <div class="mobile-button-group horizontal">
        <el-button class="m-r-4" @click="closeDialog"
          >{{ t('system.parameterConfig.cancel') }}
        </el-button>
        <el-button type="primary" @click="submit">{{ t('wholesalOrder.add') }}</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { getInventoryEnumApi, getInventoryListApi } from '@/api/wholesalOrder'
import { getWarehouseListApi } from '@/api/warehouse'
import { Dialog } from '@/components/Dialog'
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/store/modules/app'

const props = defineProps({
  type: {
    type: Number,
    default: 1 // 1: 正常选择商品 2: 异常选择商品（shopify 订单,product_id为0或者wid为0）
  },
  multiple: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['exposeMultipleData'])
const { t } = useI18n()
const tableRef = ref()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const isReset = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])

// 行样式函数
const getRowClassName = ({ row }: { row: any }) => {
  const shouldHighlight = row.is_sale === 0 || row.is_sale === '0' || row.is_sale === false
  return shouldHighlight ? 'sale-row' : ''
}

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  product: '',
  wid: '',
  brand: '',
  is_futures: '',
  date: [],
  start_time: '',
  end_time: '',
  type: 1,
  currency: 214
})

const warehouseList = ref<Array<Record<string, any>>>([])
const warehouseTypeList = ref<Array<Record<string, any>>>([])
const brandList = ref<Array<Record<string, any>>>([])

// 移动端卡片选择处理
const mobileMultipleSelection = ref<any[]>([])
const handleCardSelection = (item: any) => {
  if (item.checked) {
    if (!mobileMultipleSelection.value.some((selected) => selected.unique === item.unique)) {
      mobileMultipleSelection.value.push(item)
    }
  } else {
    mobileMultipleSelection.value = mobileMultipleSelection.value.filter(
      (selected) => selected.unique !== item.unique
    )
  }
}

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  if (val.length > 1 && !props.multiple) {
    const firstSelection = val[0]
    tableRef.value.clearSelection()
    tableRef.value.toggleRowSelection(firstSelection, true)
    multipleSelection.value = [firstSelection]
  } else {
    multipleSelection.value = val
  }
}

//点击添加按钮
const submit = () => {
  console.log(666, multipleSelection.value)
  // 为什么要加这个
  if (isMobile.value) {
    multipleSelection.value = mobileMultipleSelection.value
  }
  console.log(666, multipleSelection.value)
  if (!multipleSelection.value.length) return ElMessage.warning('请勾选商品')
  if (!areIdsEqual(multipleSelection.value, 'fl_warehouse_id')) {
    return ElMessage.warning('勾选的商品仓库必须统一，不可跨一级仓库')
  } else {
    emit('exposeMultipleData', multipleSelection.value)
    closeDialog()
  }
}

//判断数组每一项指定字段是否相同
const areIdsEqual = (array: any[], key?: string) => {
  const firstId = array[0][key ?? 'id']
  return array.every((item: Record<string, any>) => item[key ?? 'id'] === firstId)
}

//一维数组去重
const deduplication = (val: any[], key?: string) => {
  if (!val || !val.length) return
  return val.reduce((acc, item) => {
    if (!acc.some((x: Record<string, any>) => x[key ?? 'id'] === item[key ?? 'id'])) {
      acc.push(item)
    }
    return acc
  }, [])
}

//点击取消关闭弹框
const closeDialog = () => {
  reset()
  dialogVisible.value = false
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getInventoryEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  warehouseTypeList.value = resp.data.is_futures
  const resp2 = await getWarehouseListApi({})
  warehouseList.value = resp2.data.list
}

//初始化请求
const getList = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getInventoryListApi(params)
  dataList.value = resp.data.list
  if (isMobile.value) {
    dataList.value.forEach((item: Record<string, any>) => {
      if (multipleSelection.value.some((selected) => selected.unique === item.unique)) {
        item.checked = true
      } else {
        item.checked = false
      }
    })
  }
  paginationTotal.value = resp.data.total
  tableLoading.value = false

  if (2 == props.type) {
    // 异常选择商品是单选的，所有搜索建议清空选中结果
    tableRef.value.clearSelection() // 清空表格选中状态
    multipleSelection.value = [] // 清空选中数据
  }
}

const getMaxContentLength = (columnKey) => {
  // 计算内容最大长度
  return Math.max(...dataList.value.map((item) => item[columnKey]?.length || 0))
}

//重置查询项
const reset = (isRequest?: boolean) => {
  form.value = {
    product: '',
    wid: '',
    brand: '',
    is_futures: '',
    date: [],
    start_time: '',
    end_time: '',
    type: props.type,
    currency: 214
  }
  isReset.value = false
  paginationTotal.value = 0
  multipleSelection.value = []
  nextTick(() => {
    if (!isMobile.value) {
      tableRef!.value!.clearSelection()
    }
  })
  if (isRequest) {
    getList()
    isReset.value = true
  }
}

const exceptionDetails = ref<any>({}) // 异常商品搜索条件
// 是否禁用商品搜索
const isDisabledProduct = computed(() => {
  const isDisabled =
    props.type == 2 && form.value.product != '' && exceptionDetails?.value.product_name
  return isDisabled
})

// 是否禁用仓库搜索
const isDisabledWid = computed(() => {
  const isDisabled = props.type == 2 && form.value.wid > 0 && exceptionDetails?.value.wid > 0
  return isDisabled
})
/**
 * 初始化
 * @param val 商品列表
 * @param currency 币种
 * @param exceptionDetails 异常商品搜索条件
 */
const initialize = (val: any[], currency?: number, exceptionDetails?: any) => {
  getDropDownBoxInfo()
  form.value.currency = currency
  if (isMobile.value) {
    multipleSelection.value = val
    mobileMultipleSelection.value = JSON.parse(JSON.stringify(val))
  }

  if (2 == props.type) {
    // 异常选择商品
    form.value.type = 2 // 异常校对 显示 全部库村包括不可售
    if (exceptionDetails) {
      exceptionDetails.value = exceptionDetails
      // 异常选择商品
      if (exceptionDetails.product_name) {
        form.value.product = exceptionDetails.product_name
      }
      if (exceptionDetails.wid) {
        form.value.wid = exceptionDetails.wid
      }
      if (exceptionDetails.is_futures > -1) {
        form.value.is_futures = exceptionDetails.is_futures
      }
    }
  }

  nextTick(() => {
    getList()
  })

  selectionPak.value = val
  if (isMobile.value) {
    return false
  }
  if (!val || !val.length) return
  val.forEach((item: Record<string, any>) => {
    nextTick(() => {
      tableRef!.value!.toggleRowSelection(item, true)
    })
  })
}

defineExpose({
  dialogVisible,
  initialize
})
</script>

<style lang="less" scoped>
@media (width <= 768px) {
  .product-card {
    margin-bottom: 12px;

    .card-header {
      .product-name {
        font-size: 13px;
      }
    }

    .card-content {
      .info-row {
        margin-bottom: 6px;

        .label {
          min-width: 70px;
          font-size: 12px;
        }

        .value {
          font-size: 12px;
        }
      }
    }
  }
}

:deep(.el-table__row.sale-row) {
  background-color: #fff3cd !important;
}

:deep(.el-table__row.sale-row:hover) {
  background-color: #ffeaa7 !important;
}

:deep(.el-table__row.sale-row > td) {
  background-color: #fff3cd !important;
}

:deep(.el-table__row.sale-row:hover > td) {
  background-color: #ffeaa7 !important;
}

// 移动端卡片的销售状态样式
.sale-card {
  background-color: #fff3cd !important;
  border-color: #ffeaa7 !important;
}

.sale-card:hover {
  background-color: #ffeaa7 !important;
}

.product-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .product-name {
      margin-right: 12px;
      font-size: 14px;
      font-weight: 600;
      flex: 1;
    }
  }

  .card-content {
    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 13px;

      .label {
        min-width: 80px;
        font-weight: 500;
        color: #666;
      }

      .value {
        color: #333;
        text-align: right;
        flex: 1;
      }
    }
  }
} // 移动端商品卡片样式// 销售状态行的样式
</style>
